from django.db import models
from django.contrib.auth.models import User, Group

PERMISSION = [
            ('can_submit_ticket', '可以提交工单'),
            ('can_view_own_ticket', '可以查看自己的工单'),
            ('can_view_all_ticket', '可以查看所有工单'),
            ('can_approve_level1_ticket', '一级审批'),
            ('can_approve_level2_ticket', '二级审批'),
            ('can_approve_level3_ticket', '三级审批'),
            ('can_approve_level4_ticket', '四级审批'),
            ('can_approve_final_tickets', '终极审批'),
            ('can_manage_system_tickets', '可以管理系统工单'),
            ('can_manage_database_tickets', '可以管理数据库工单'),
        ]

TICKET_TYPE_CHOICES = [
        ('database', '数据库工单'),
        ('system', '系统工单'),
    ]

STATUS_CHOICES = [
        ('pending', '未提交'),
        ('submitted', '待审批'),
        ('level1_approved', '一级审批通过'),
        ('level1_rejected', '一级审批未通过'),
        ('level2_approved', '二级审批通过'),
        ('level2_rejected', '二级审批未通过'),
        ('level3_approved', '三级审批通过'),
        ('level3_rejected', '三级审批未通过'),
        ('level4_approved', '四级审批通过'),
        ('level4_rejected', '四级审批未通过'),
        ('final_approved', '终极审批通过'),
        ('final_rejected', '终极审批未通过'),
        ('rejected', '工单已驳回'),
        ('completed', '工单已完成'),
    ]

class Ticket(models.Model):
    title = models.CharField(max_length=200, verbose_name='工单标题')
    description = models.TextField(verbose_name='工单描述')
    ticket_type = models.CharField(max_length=20, choices=TICKET_TYPE_CHOICES, default='database', verbose_name='工单类型')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_tickets', verbose_name='创建者')
    executor = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='executed_tickets',verbose_name='执行者')
    status = models.CharField(max_length=20,choices=STATUS_CHOICES,default='pending',verbose_name='状态')
    operation_target = models.CharField(max_length=255,null=True,blank=True,verbose_name='操作对象',help_text='具体的操作目标，例如数据库表、系统模块等')
    approval_process = models.ForeignKey('ApprovalProcess',on_delete=models.SET_NULL,null=True,blank=True,related_name='tickets',verbose_name='审批流程')
    current_group = models.ForeignKey(Group,on_delete=models.SET_NULL,null=True,blank=True,verbose_name='当前审批组')
    remark = models.TextField(verbose_name='备注',null=True,blank=True,help_text='添加任何额外说明或备注信息')
    attachment = models.FileField(upload_to='attachments/',null=True,blank=True,verbose_name='附件',help_text='上传相关文件或文档')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    def save(self, *args, **kwargs):
        # 自动关联审批流程
        if not self.approval_process:
            try:
                self.approval_process = ApprovalProcess.objects.get(process_type=self.ticket_type)
            except ApprovalProcess.DoesNotExist:
                raise ValueError(f"没有找到与工单类型 '{self.ticket_type}' 对应的审批流程")

        super().save(*args, **kwargs)

    class Meta:
        verbose_name = '工单'
        verbose_name_plural = '工单'

        permissions = PERMISSION

    def __str__(self):
        return self.title


class ApprovalProcess(models.Model):
    name = models.CharField(max_length=100, verbose_name='审批流程名称')
    process_type = models.CharField(max_length=20, choices=TICKET_TYPE_CHOICES, verbose_name='工单类型')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '审批流程'
        verbose_name_plural = '审批流程'

    def __str__(self):
        return self.name


class ApprovalStep(models.Model):
    process = models.ForeignKey(ApprovalProcess, on_delete=models.CASCADE, related_name='steps', verbose_name='审批流程')
    step_number = models.PositiveIntegerField(verbose_name='审批步骤')
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name='审批组')

    class Meta:
        verbose_name = '审批步骤'
        verbose_name_plural = '审批步骤'
        ordering = ['step_number']

    def __str__(self):
        return f"{self.process.name} - Step {self.step_number} ({self.group.name})"


class ApprovalRecord(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name='approvals', verbose_name='工单')
    step = models.ForeignKey(ApprovalStep, on_delete=models.CASCADE, verbose_name='审批步骤')
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name='审批组')
    approved_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='审批人')
    approved_at = models.DateTimeField(auto_now_add=True, verbose_name='审批时间')
    status = models.CharField(max_length=20, choices=[('approved', '通过'), ('rejected', '拒绝')], verbose_name='审批状态')
    comments = models.TextField(null=True, blank=True, verbose_name='审批意见')

    class Meta:
        verbose_name = '审批记录'
        verbose_name_plural = '审批记录'
        ordering = ['approved_at']

